from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver import ChromeOptions
from time import sleep
import openpyxl

# 创建 WebDriver 对象，指明使用chrome浏览器驱动
option=ChromeOptions()
option.add_experimental_option('excludeSwitches',['enable-automation'])
option.add_argument("--disable-blink-features=AutomationControlled")
wd = webdriver.Chrome(service=Service(r'D:\soft\selenium\chromedriver.exe'),options=option)
script='''object.defineProperty(navigator,'webdriver',{undefinedget:()=>undefined}'''
wd.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument",{"source":script})

# 调用WebDriver 对象的get方法 可以让浏览器打开指定网址
wd.get('http://*************&agentName=')

#窗口最大化
wd.maximize_window()

# #创建文件对象
# book = openpyxl.Workbook()
# sh=book.active
row=1

#列表主页界面
mainWindow = wd.current_window_handle



#列表
while True:
    if row==100:
        break

    elements=wd.find_elements(By.CSS_SELECTOR,'body > div  div.vT_z > div > div > div.vT-srch-result-list > ul > li > a')
    for e in elements:
        # print(e.text)
        e.click()

        windows = wd.window_handles
        wd.switch_to.window(windows[-1])
        sleep(1)

        wd.find_element(By.XPATH,'//*[@id="hideGG"]').click()
        sleep(1)

        project_name=wd.find_element(By.XPATH,'//*[@id="detail"]/div[2]/div/div[2]/div/div[1]/h2').text
        purchasing_unit=wd.find_element(By.XPATH,'//*[@id="detail"]/div[2]/div/div[2]/div/div[2]/table/tbody/tr[4]/td[2]').text
        bid_winning_amount=wd.find_element(By.XPATH,'//*[@id="detail"]/div[2]/div/div[2]/div/div[2]/table/tbody/tr[7]/td[2]').text

        print(f'采购单位：{purchasing_unit}，中标价格：{bid_winning_amount}，项目名称：{project_name}')


        sleep(1)
        wd.close()
        row+=1
        wd.switch_to.window(mainWindow)
        sleep(1)

    sleep(5)
    wd.find_element(By.CSS_SELECTOR,'div.vT_z div > div.vT-srch-result-list > p.pager a.next').click()
    sleep(3)

